package com.seres.oplogs;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.seres.client.mapper.log.SysLogMapper;
import com.seres.client.model.log.SysLog;
import com.seres.config.CacheInterface;
import com.seres.enums.ErrorEnum;
import com.seres.enums.OftenEnum;
import com.seres.redis.RedisTableCache;
import com.seres.util.ValidatorTools;
import com.seres.vo.AuthUserInfo;
import com.seres.vo.SysInterface;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class OplogServiceImpl  implements OplogService {

    @Autowired
    private SysLogMapper logMapper;

    @Autowired
    private RedisTableCache redisTableCache;

    @Autowired
    private CacheInterface urlCache;

@Override
    public void createErrorLog(HttpServletRequest request, ErrorEnum errorEnum, String msg) {
        String url = request.getRequestURI();
        SysInterface sysInterface = urlCache.getInterface(url);
        if (sysInterface == null) {
            log.error("该接口不存在缓存中：{}", url);
            return;
        }
        Map<String, String[]> map = request.getParameterMap();
//        long time = Long.parseLong(request.getAttribute("times").toString());
        SysLog sysLog = SysLog.builder()
                .ip(ValidatorTools.getIpAddr(request))
                .methodType(request.getMethod())
                .moduleName(sysInterface.getClassRemark())
//                .times(System.currentTimeMillis() - time)
                .title(sysInterface.getRemarks())
                .type(getType(sysInterface.getToken()))
                .url(request.getRequestURI())
                .userId(getUserId(sysInterface.getToken()))
                .code(errorEnum.getCode())
                .errorMsg(StringUtils.isNotBlank(msg) ? msg : errorEnum.getMsg())
                .requestParam(getParam(map))
                .build();
        try {
            logMapper.insert(sysLog);
        } catch (Throwable e) {
            log.error("插入日志失败：{}", e);
        }
    }

    @Override
    public List<?> getParam(Map<String, String[]> map) {
        Map<String, Object> res = new HashMap<>();
        List<Map<String, Object>> list = new ArrayList<>();
        for (Map.Entry<String, String[]> entry : map.entrySet()) {
            res.put(entry.getKey(), entry.getValue()[0]);
        }
        list.add(res);
        return list;
    }

    @Override
    public Integer getType(boolean b) {
        if (b) {
            return OftenEnum.InterfaceType.POWER.code();
        }
        return OftenEnum.InterfaceType.PUBLIC.code();
    }

    @Override
    public Long getUserId(boolean b) {
        if (b) {
            return AuthUserInfo.getUserId();
        }
        return null;
    }

}
